﻿
// 获取当前日期时间
var now = new Date();
var year = now.getFullYear();
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var day = ("0" + now.getDate()).slice(-2);
var hours = ("0" + now.getHours()).slice(-2);
var minutes = ("0" + now.getMinutes()).slice(-2);
var seconds = ("0" + now.getSeconds()).slice(-2);
var serialNumber = year + month + day + hours + minutes + seconds;
var inputElement = document.getElementById('allocationNo');
inputElement.value = serialNumber;
console.log(inputElement.value)

var checkAll;
var checkpll;
var Show;
var Fenye;
var close;
var idsArray = [];
var tidsArray = [];

layui.use(function () {
    var $ = layui.$;
    var layer = layui.layer;
    var util = layui.util;
    var form = layui.form;
    var table = layui.table;


    // 定义获取选中复选框值的函数
    function getCheckedCheckboxValues() {
        var checkedCheckboxValues = [];
        $("input[name='ckbproc']:checked").each(function () {
            checkedCheckboxValues.push($(this).val());
        });
        return checkedCheckboxValues;
    }

    // 事件
    util.on('lay-on', {
        'test-page-custom': function () {
            layer.open({
                type: 1,
                area: ['900px', '600px'],
                resize: false,
                shadeClose: true,
                title: '选择产品',
                content: `
           <form class="layui-form" action="">
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">产品编号:</label>
                <div class="layui-input-block">
                    <input type="text" id="productNos" name="productNo" placeholder="请输入" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">产品名称:</label>
                <div class="layui-input-block">
                    <input type="text" id="productNames" name="productName" placeholder="请输入" autocomplete="off" class="layui-input">
                </div>
            </div>
            <div class="layui-inline">
                <div class="layui-btn-container">
                    <button type="button" class="layui-btn layui-bg-blue" onclick="Fenye()">
                        <i class="layui-icon layui-icon-search"></i>搜索
                    </button>
                </div>
            </div>
        </div>
    </form>
    <div>
    <table class="layui-table">
    <tr>
        <th>
            <input type="checkbox" id="checkAll" onclick="checkAll()" value="" />
       </th>
        <th>产品编号</th>
        <th>产品名称</th>
        <th>规格</th>
        <th>存储单位</th>
        <th>包装类型</th>
        <th>价格</th>
        <th>重量</th>
        <th>显示名</th>
    </tr>
    <tbody id="data"></tbody>
</table>
    </div>
    <div id="demo-laypage-layout"></div>
    <div style="text-align:right;margin-top:30px">
    <button type="button" class="layui-btn layui-btn-primary layui-btn-sm" id="closePopupBtn" onclick="close()">
                        关闭
                    </button>
    <button type="button" class="layui-btn layui-bg-blue layui-btn-sm" >
                        选择
                    </button>
    </div>

        `,
                success: function () {
                    // 对弹层中的表单进行初始化渲染
                    form.render();
                    // 表单提交事件
                    form.on('submit(demo-login)', function (data) {
                        var field = data.field; // 获取表单字段值
                        return false; // 阻止默认 form 跳转
                    });

                    //获取复选框值
                    var chooseButton = $(".layui-btn.layui-bg-blue:last");
                    chooseButton.on('click', function () {
                        var checkedValues = getCheckedCheckboxValues();
                        if (checkedValues.length > 0) {
                            idsArray = checkedValues
                            console.log("选中的复选框值:", checkedValues, idsArray);
                            layer.close(pageIndex);


                            //显示
                            layui.use('table', function () {
                                var form = layui.form;
                                var table = layui.table;
                                $.ajax({
                                    url: '../Warehouse/GetAllocationProductRangeModel', // 后端接口地址，需替换为实际地址
                                    type: 'post',
                                    data: { productId: JSON.stringify(idsArray), token: localStorage.getItem("token") },
                                    success: function (res) {
                                        console.log(res)
                                        var res = JSON.parse(res)
                                        //console.log(res)
                                        //console.log(idsArray)
                                        // res 是从后端获取到的 JSON 数据
                                        if (res.code === 0) {
                                            console.log(res.data);
                                            tidsArray.push(res.data)
                                            console.log(tidsArray);
                                            table.render({
                                                elem: allocationProduct, // 对应 HTML 中表格的 id
                                                data: res.data, // 绑定获取到的数据
                                                //page: true,
                                                //limit: 5,
                                                //limits: [5, 8, 10],
                                                cols: [[
                                                    { type: 'checkbox', fixed: 'left' },
                                                    { field: 'productName', title: '产品名称' },
                                                    { field: 'productNo', title: '产品编号' },
                                                    { field: 'productSpec', title: '规格' },
                                                    { field: 'productBatch', title: '批次' },
                                                    { field: 'productPrice', title: '单价' },
                                                    { field: 'quantity', title: '数量', edit: 'text' },
                                                    { field: 'binLocationName', title: '原库位' },
                                                    {
                                                        field: '', title: '操作', width: 200, templet: function (d) {
                                                            return '<a class="layui-btn layui-btn-edit layui-btn-xs" lay-on="test-page-delete"><i class="layui-icon layui-icon-edit"></i>删除</a> ';
                                                        }
                                                    }
                                                ]]
                                            });

                                        } else {
                                            console.log(res.msg);
                                        }
                                    },
                                    error: function () {
                                        console.log('获取数据失败');
                                    }
                                });
                            });


                        } else {
                            layer.msg("请至少选择一项");
                        }
                    });
                    //关闭弹窗
                    close = function () {
                        layer.close(index);
                    }
                }
            });
            var pageIndex = 1;
            var pageSize = 6;
            var tacount = 0;
            $(function () {
                Fenye();
            });
            Show1 = function () {
                var productNo = $("#productNos").val();
                var productName = $("#productNames").val();
                $.ajax({
                    url: '../Warehouse/GetProductStorageListShow',
                    async: false,//改为异步,
                    type: 'get',
                    data: {
                        productNo: productNo,
                        productName: productName,
                        pageIndex: pageIndex,
                        pageSize, pageSize,
                        token: localStorage.getItem("token")
                    },
                    success: function (res) {
                        var list = '';
                        var parsedData = JSON.parse(res);
                        console.log(parsedData)
                        $(parsedData.data.list).each(function () {
                            list += `
                         <tr>
                        <td>
                                <input type="checkbox" name="ckbproc" value="${this.productId}" />
                            </td>
                         <td>${this.productNo}</td>
                          <td>${this.productName}</td>
                          <td>${this.productSpec}</td>
                          <td>${this.productSpec}</td>
                          <td>${this.productWrap}</td>
                          <td>${this.productPrice}</td>
                          <td>${this.productWeight}</td>
                                  <td>
                                     
                                    </td>
                     </tr> `
                        });
                        $("#data").html(list);
                        tacount = parsedData.data.totalCount;
                    }
                })
            }

            //分页
            Fenye = function () {

                layui.use(function () {
                    var laypage = layui.laypage;
                    // 完整显示
                    Show1()
                    laypage.render({
                        elem: 'demo-laypage-layout', // 元素 id
                        count: tacount, // 数据总数
                        limit: pageSize,//2.设置默认分页大小
                        limits: [6, 10, 15],//3.设置分页组件可选的分页大小
                        layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip'], // 功能布局
                        jump: function (obj) {
                            console.log(obj);
                            pageIndex = obj.curr;
                            pageSize = obj.limit;
                            Show1();
                        }
                    });
                });
            }


            checkpll = function () {
                var checkedIds = $("input[name='ckbproc']:checked");//取所有选中的name=ckbproc的复选框集合
                var ids = [];//定义了一个数组,空的
                $(checkedIds).each(function (i, obj) {
                    var id = $(obj).val();
                    ids.push(id);//往数组里push数字,数字就是我们的商品id
                });

                console.log(ids)
            }
            checkAll = function () {

                var checked = $("#checkAll").prop("checked");  //取全选/反选 checkbox的选中状态值
                $("input[name='ckbproc']").prop("checked", checked);//把所有name=ckbproc的checkbox的选中状态赋值为 checked
                console.log(checked)
            }


        }
    })


    //反填
    function fantian() {
        return new Promise((resolve, reject) => {
            // 获取要编辑的用户ID
            const allocationId = localStorage.getItem("allocationId");
            console.log(allocationId);
            if (allocationId) {
                // 发送AJAX请求获取数据
                $.ajax({
                    type: "get",
                    url: "/Warehouse/GetFanAllocation",
                    data: {
                        allocationId: allocationId,
                        token: localStorage.getItem("token")
                    },
                    success: (res) => {
                        try {
                            const { data } = JSON.parse(res);
                            //console.log(data)
                            if (data) {
                                const { allocationProductList } = data;
                                var allocation = data;
                                console.log(allocation);
                                console.log(allocationProductList);
                                // 反填表单的函数
                                fillForm(allocation);
                                // 渲染表格的函数
                                renderTable(allocationProductList);
                                resolve(allocation, allocationProductList);
                            } else {
                                layui.layer.msg(res.message, { icon: 2 });
                                reject(res.message);
                            }
                        } catch (e) {
                            console.error(e);
                            layui.layer.msg('数据解析失败，请稍后重试', { icon: 2 });
                            reject('数据解析失败');
                        }
                    },
                    error: () => {
                        layui.layer.msg('获取用户信息失败，请稍后重试', { icon: 2 });
                        reject('获取用户信息失败');
                    }
                });
            } else {
                reject('未获取到有效的仓库ID');
            }
        });
    }
    var obj = {
        allocationId: 0,
        allocationStatus: '',
        warehouseId: '',
        examineReason: '',
        examinePeople: '',
        examineTime: '',
        officeId: '',
        userid: '',
        createName: '',
        createTime: '',
        updateName: '',
        updateTime: '',
        deleteName: '',
        deleteTime: ''
    };
    // 反填表单的函数
    function fillForm(allocation) {
        //form.render('select');
        $('#allocationNo').val(allocation.allocationNo);
        $('#warehouseId').val(allocation.warehouseId);
        form.render('select');
        $('#associateNumber').val(allocation.associateNumber);
        $('#singleMaker').val(allocation.singleMaker);
        $('#allocationRemarks').val(allocation.allocationRemarks);
        const date = new Date(allocation.singleTime);
        const year = date.getFullYear();
        const month = ("0" + (date.getMonth() + 1)).slice(-2);
        const day = ("0" + date.getDate()).slice(-2);
        $('#singleTime').val(year + "-" + month + "-" + day);
        $('#storageRemarks').val(allocation.storageRemarks);

        obj.allocationId = allocation.allocationId
        obj.allocationStatus = allocation.allocationStatus
        obj.warehouseId = allocation.warehouseId
        obj.examineReason = allocation.examineReason
        obj.examinePeople = allocation.examinePeople
        obj.examineTime = allocation.examineTime
        obj.officeId = allocation.officeId
        obj.userid = allocation.userid
        obj.createName = allocation.createName
        obj.createTime = allocation.createTime
        obj.updateName = allocation.updateName
        obj.updateTime = allocation.updateTime
        obj.deleteName = allocation.deleteName
        obj.deleteTime = allocation.deleteTime
        console.log(obj)
        // 重新渲染表单元素（如果有）
        
    }

    // 渲染表格的函数
    function renderTable(allocationProductList) {
        console.log(allocationProductList);
        var allocationId = allocationProductList.allocationId
        layui.use('table', function () {
            var table = layui.table;
            //查询
            $.ajax({
                type: "get",
                url: "/Warehouse/GetFanAllocation",
                data: {
                    allocationId: allocationId,
                    token: localStorage.getItem("token")
                },
                success: function (res) {
                    var obj = JSON.parse(res);
                    console.log(obj)
                    if (obj.code === 0) {
                        var inst = table.render({
                            elem: '#allocationProduct',//对应HTML中表格的id
                            data: allocationProductList,//绑定获取的数据
                            cols: [[
                                { type: 'checkbox', fixed: 'left' },
                                { field: 'productName', title: '产品名称' },
                                { field: 'productNo', title: '产品编号' },
                                { field: 'productSpec', title: '规格' },
                                { field: 'productBatch', title: '批次' },
                                { field: 'productPrice', title: '单价' },
                                { field: 'quantity', title: '数量', edit: 'text' },
                                { field: 'binLocationName', title: '原库位' },
                                {
                                    field: '', title: '操作', width: 200, templet: function (d) {
                                        return '<a class="layui-btn layui-btn-edit layui-btn-xs" lay-on="test-page-delete"><i class="layui-icon layui-icon-edit"></i>删除</a> ';
                                    }
                                }
                            ]]
                        })
                    } else {
                        console.log(res.msg);
                    }
                },
                error: function () {
                    console.log("获取数据失败");
                    // 可以考虑显示一个错误消息给用户
                }
            });

        });
    }


    //文档就绪函数
    $(function () {
        //generateDate();
        fantian();
    })



    //修改调拨
    var obj1 = {
        allocationId: 0,
        allocationNo: "",
        warehouseId: "",
        aWarehouseName: "",
        associateNumber: "",
        singleMaker: "",
        singleTime: "",
        allocationRemarks: "",
        allocationStatus: "",
        examineReason: "",
        examinePeople: "",
        examineTime: "",
        officeId: "",
        userid: 0,
        createName: "",
        createTime: "",
        isDelete: false,
        allocationProdutesList: []
    };
    layui.use(['layer', 'form', 'util', 'table'], function () {
        var layer = layui.layer;
        var $ = layui.jquery;
        var form = layui.form;
        var util = layui.util;
        var table = layui.table;

        form.on('submit(formSubmit)', function (data) {
            var field = data.field;
            var checkStatus = table.checkStatus('allocationProduct');
            field.allocationProdutesList = checkStatus.data.map(function (item) {
                return item;
            });
            console.log(field);//field.products

            obj1.allocationId = obj.allocationId
            obj1.allocationNo = field.allocationNo
            obj1.warehouseId = obj.warehouseId
            obj1.aWarehouseName = field.aWarehouseName
            obj1.associateNumber = field.associateNumber
            obj1.singleMaker = field.singleMaker
            obj1.singleTime = field.singleTime
            obj1.allocationRemarks = field.allocationRemarks
            obj1.allocationStatus = obj.allocationStatus
            obj1.examineReason = obj.examineReason
            obj1.examinePeople = obj.examinePeople
            obj1.examineTime = obj.examineTime
            obj1.createName = obj.createName
            obj1.createTime = obj.createTime
            obj1.updateName = obj.updateName
            obj1.deleteName = obj.deleteName
            obj1.deleteTime = obj.deleteTime
            obj1.allocationProdutesList = field.allocationProdutesList
            console.log(obj1)
            //显示填写结果，仅作演示用
            $.ajax({
                url: '/Warehouse/GetUpdAllocation',
                type: 'post',
                data: {
                    field: obj1,
                    token: localStorage.getItem("token"),
                },
                success: function (res) {
                    var res = JSON.parse(res)
                    console.log(obj1);
                    console.log(res);
                    if (res.code == 0) {
                        layer.alert("修改成功");
                        //跳转页面
                        location.href = '/Warehouse/AllocationShow'
                    } else {
                        layer.alert("修改失败");
                    }
                }
            });

            return false; // 阻止默认 form 跳转
        });
    });



    

});
// 定义时间格式转换函数
function formatTime(timeStamp) {
    if (timeStamp) {
        var date = new Date(timeStamp);
        var year = date.getFullYear();
        var month = ('0' + (date.getMonth() + 1)).slice(-2);
        var day = ('0' + date.getDate()).slice(-2);
        var hour = ('0' + date.getHours()).slice(-2);
        var minute = ('0' + date.getMinutes()).slice(-2);
        var second = ('0' + date.getSeconds()).slice(-2);
        return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
    }
    return "";
}


